
use crate::handlers::{download::DownloadState, process::ProcessState};

pub mod file_utils;
pub mod progress;

#[derive(Debug, Clone)]
pub struct AppState {
    pub config: AppConfig,
    pub download_state: DownloadState,
    pub process_state: ProcessState,
}

#[derive(Debug, Clone, serde::Deserialize)]
pub struct AppConfig {
    #[serde(default = "default_server_port")]
    pub server_port: u16,
    
    #[serde(default = "default_pbf_source_url")]
    pub pbf_source_url: String,
    
    #[serde(default = "default_pbf_download_dir")]
    pub pbf_download_dir: String,
    
    #[serde(default = "default_temp_dir")]
    pub temp_dir: String,
    
    #[serde(default = "default_tiles_output_dir")]
    pub tiles_output_dir: String,
    
    #[serde(default = "default_max_download_speed")]
    pub max_download_speed: u64, // KB/s
    
    #[serde(default = "default_max_concurrent_tasks")]
    pub max_concurrent_tasks: usize,
}

impl AppConfig {
    pub fn load() -> Result<Self, config::ConfigError> {
        Ok(AppConfig {
            server_port: default_server_port(),
            pbf_source_url: default_pbf_source_url(),
            pbf_download_dir: default_pbf_download_dir(),
            temp_dir: default_temp_dir(),
            tiles_output_dir: default_tiles_output_dir(),
            max_download_speed: default_max_download_speed(),
            max_concurrent_tasks: default_max_concurrent_tasks(),
        })
    }
    
    pub fn pbf_download_path(&self) -> String {
        let filename = self.pbf_source_url.split('/').last().unwrap_or("china-latest.osm.pbf");
        format!("{}/{}", self.pbf_download_dir, filename)
    }
}

fn default_server_port() -> u16 {
    3000
}

fn default_pbf_source_url() -> String {
    "https://download.geofabrik.de/asia/china-latest.osm.pbf".to_string()
}

fn default_pbf_download_dir() -> String {
    "data/pbf".to_string()
}

fn default_temp_dir() -> String {
    "data/temp".to_string()
}

fn default_tiles_output_dir() -> String {
    "data/tiles".to_string()
}

fn default_max_download_speed() -> u64 {
    10240 // 10MB/s
}

fn default_max_concurrent_tasks() -> usize {
    4
}
